package com.wjb.service.Impl;

import com.wjb.mapper.ItemStockMapper;
import com.wjb.pojo.Emun.OrderStatus;
import com.wjb.pojo.dto.OrderxDto;
import com.wjb.pojo.entity.Orderx;
import com.wjb.service.ItemStockService;
import com.wjb.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.beans.Transient;
import java.util.UUID;

/**
 * @author : 王济彬
 * @date: 2025/5/24 - 05 - 24 - 16:08
 * @Description: com.wjb.service.Impl
 * @version: 1.0
 */
@Service
@Transactional
public class ItemStockServiceImpl implements ItemStockService{

    @Resource
    private ItemStockMapper itemStockMapper;

    @Autowired
    private StockService stockService;
    // 下单并扣库存
    public String createOrder(OrderxDto request) {
        // 1. 生成全局唯一的订单ID（用于幂等性）
        String orderId = UUID.randomUUID().toString();

        // 2. 扣减库存（带幂等性）
        boolean stockDeducted = stockService.deductStock(
                request.getProductId(),
                request.getQuantity(),
                orderId
        );

        if (!stockDeducted) {
            return "库存不足";
        }
        System.out.println("库存充足，已经扣除，尝试创建订单");

        try {
            // 3. 创建订单（数据库操作）
            Orderx order = new Orderx();
            order.setOrderId(orderId);
            order.setProductId(request.getProductId());
            order.setQuantity(request.getQuantity());
            order.setStatus(String.valueOf(OrderStatus.PENDING_PAYMENT));
            itemStockMapper.createOrder(order);

            // 4. 异步同步库存到数据库（实际项目中使用消息队列）
            //asyncSyncStockToDb(request.getProductId(), request.getQuantity());

            return "成功创建订单";
        } catch (Exception e) {
            // 5. 订单创建失败，回滚库存（实际项目中使用补偿机制）
            stockService.rollbackStock(request.getProductId(), request.getQuantity(), orderId);
            return "订单创建失败";
        }
    }


}
